package com.edisoncgh.controller.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class loginFilter implements Filter {
    // 重定向url
    private String redirectUrl;
    // 不需要拦截的url信息
    private String unCheckedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        System.out.println("拦截器启动...");
        //获取配置参数
        redirectUrl = "index.jsp";
        unCheckedUrls = servletContext.getInitParameter("unCheckedUrls");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 创建request和response对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取用户请求的url
        String requestedPath = request.getServletPath();

        // 如果用户请求的是不需要拦截的url，直接放行
        List<String> urls = Arrays.asList(unCheckedUrls.split(","));
        for(String url:urls) {
//            System.out.println("url" + url);
            if(requestedPath.contains(url)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        // 从session中获取SessionKey,若不存在,则直接重定向到redirectUrl去
        Object user = request.getSession().getAttribute("userId");
        System.out.println("user:" + user);
        if (user == null) {
            request.getSession().setAttribute("mention", "您还未登录！");
//            response.sendRedirect(request.getContextPath() + redirectUrl);
            response.sendRedirect(redirectUrl);
            return;
        } else {
            request.getSession().setAttribute("mention", null);
            // 若存在就可以直接放行
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
